package cn.fl.warrant.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.web.core.framework.constant.SysOrgConstant;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.warrant.service.IArcLocalContractUserService;
import cn.fl.warrant.transform.ArcLocalContractUserVOTransform;
import cn.fl.warrant.vo.ArcLocalContractUserVO;
import fl.warrant.facade.archive.condition.ArcLocalContractUserQC;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcReceiptConditionRDTO;
import net.sf.json.JSONArray;



/**
 * @Description: 属地合同管理员配置表(旧表：无) 控制层
 */
@Controller
@RequestMapping("/archive/arcLocalContractUser")
public class ArcLocalContractUserController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcLocalContractUserController.class);

	/**
	 * arcLocalContractUserService 服务层BEAN
	 */
	@Autowired
	private IArcLocalContractUserService arcLocalContractUserService;
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;//数据字典
	/**
	 * 组织架构 API 暴露服务
	 */
	@Autowired
	private ISysOrgApiService sysOrgApiService;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("archive/arcLocalContractUser/arcLocalContractMain");
		//省公司合同管理员
		List<KeyValueVO> localContList = sysDictionaryApiService.getKvList(ArchiveConstants.ARC_LOCAL_CONTRACT, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("localContList", JSON.toJSONString(localContList));
		//权证属地城市配置
		List<KeyValueVO> localCityList = sysDictionaryApiService.getKvList(ArchiveConstants.ARC_LOCAL_CITY, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("localCityList", JSON.toJSONString(localCityList));
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 初始化事业部组织架构数据列表
	 */
	@RequestMapping(value = "/initDivisionList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initDivisionList(HttpServletRequest request, HttpServletResponse response) {
		try {
			JSONArray jsonArray = new JSONArray();
			jsonArray = this.searchOrgTreeByOrgNm("", CurrentThreadContext.getCurrentSysCd()); 
			//过滤，只展示事业部数据
			//Map filterOrgMap=sysDictionaryApiService.searchGroupToMap( CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(),ArchiveConstants.ARC_FILTER_ORG);
			
			
			BaseLogUtils.info(logger, "initDivisionList", "初始化组织架构列表页面.",CurrentThreadContext.getCurrentUserName());
			return jsonArray;
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initDivisionList", "初始化组织架构列表页面失败.系统错误:"+e.getMessage(),CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}
	public JSONArray searchOrgTreeByOrgNm(String orgNm, String sysCd) throws Exception{
		List<SysOrgDTO> orgList = this.sysOrgApiService.searchOrgTreeByOrgNm(orgNm, sysCd);
		//组织架构二级列表，过滤非事业部
		List<KeyValueVO> filterOrgList= this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC_FILTER_ORG, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		if(!orgList.isEmpty()) {
			//组织架构二级列表，过滤非事业部
		  for (Iterator<SysOrgDTO> it = orgList.iterator(); it.hasNext();) {
			  SysOrgDTO jb = (SysOrgDTO)it.next();
			  if(StringUtils.isNotBlank(jb.getOrgCd())) {
				if(CollectionUtils.isNotEmpty(filterOrgList)) {
					String orgCd = jb.getOrgCd().toString();
					for (int i = 0; i < filterOrgList.size(); i++) {
						KeyValueVO kv=filterOrgList.get(i);
						if (kv.getKey().equals(orgCd)) {
							it.remove();
						}
					}
				}
			};
		 }
	   }
		JSONArray jsonArray = new JSONArray ();
		if(CollectionUtils.isEmpty(orgList)){
			return jsonArray;
		}
		for (SysOrgDTO sysOrgDTO : orgList) {
			JSONObject obj = new JSONObject();
			obj.put("ischecked", false);
			obj.put("id", sysOrgDTO.getId());
			obj.put("text", sysOrgDTO.getOrgNm());
			obj.put("pid", sysOrgDTO.getOrgPid());
			obj.put("orgCd", sysOrgDTO.getOrgCd());
			obj.put("orgDispNm", sysOrgDTO.getOrgDispNm());
			obj.put("orgLvl", sysOrgDTO.getOrgLvl());
			jsonArray.add(obj);
		}
		JSONArray treeList = this.treeList(jsonArray,SysOrgConstant.SYS_ORG_CD_PID_INIT);
		return treeList;
	}
	/**
	 * 递归添加整个集合数据
	 *
	 * @param treeList
	 * @param parentId
	 * @return
	 */
	private JSONArray treeList(List treeList, Long parentId) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "treeList", "获取机构树开始");

		List list = this.treeList1(treeList, parentId.toString());
		JSONArray rtnArray = JSONArray.fromObject(list);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "treeList", "获取机构树.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return rtnArray;
	}
	/**
	 * 递归添加整个集合数据
	 *
	 * @param treeList
	 * @param parentId
	 * @return
	 */
	private List treeList1(List<Map<String, Object>> treeList, String parentId) {
		List childMenu = new ArrayList();
		for (Map object : treeList) {
			String oid = object.get("id").toString();
			String pid = object.get("pid").toString();
			if (parentId.equals(pid)) {
				List c_node = treeList1(treeList, oid);
				object.put("children", c_node);
				childMenu.add(object);
			}
		}
		return childMenu;
	}
	
	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String orgId = request.getParameter("orgId");
		String orgCd = request.getParameter("orgCd");
		ArcLocalContractUserVO vo =new ArcLocalContractUserVO();
		if(StringUtils.isNotEmpty(id)){
			vo = this.arcLocalContractUserService.selectById(Long.valueOf(id));
		}
		ModelAndView view = new ModelAndView("archive/arcLocalContractUser/arcLocalContractModify");
		//省公司合同管理员
		List<KeyValueVO> localContList = sysDictionaryApiService.getKvList(ArchiveConstants.ARC_LOCAL_CONTRACT, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		//List<SysDictionaryDTO> localContList = sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), ArchiveConstants.ARC_LOCAL_CONTRACT);
		if(vo!=null) {
		//赋值省合同管理员勾选项 
			setContIsSelect(localContList,vo);
		}
		view.addObject("localContList", localContList);
		//权证属地城市配置
		List<KeyValueVO> localCityList = sysDictionaryApiService.getKvList(ArchiveConstants.ARC_LOCAL_CITY, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("localCityList", localCityList);
		view.addObject("id", id);
		view.addObject("contVO", vo);
		view.addObject("orgId",orgId);
		view.addObject("orgCd",orgCd);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	//设置省公司合同管理员是否勾选
	@SuppressWarnings("unchecked")
	private void setContIsSelect(List<KeyValueVO> localContList,ArcLocalContractUserVO vo) {
		if(StringUtils.isNotBlank(vo.getUserIds())) {
			String userIds= vo.getUserIds();
			String[] userIdsStr=userIds.split(";");//分割成数组
			for(KeyValueVO obj:localContList) {
				for(int i = 0; i < userIdsStr.length; i++){
					userIds=";"+userIds;
					if(userIds.contains(obj.getKey())) {
						obj.setIsHide(true);
					}
				}
			}
		}	
	}
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String orgCode = request.getParameter("orgCode");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		ArcLocalContractUserQC qc = new ArcLocalContractUserQC();
		if (StringUtils.isNotEmpty(orgCode)) {
			qc.setOrgCode(orgCode);
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.arcLocalContractUserService.searchListPage(page);
		List<ArcLocalContractUserVO> list = (List<ArcLocalContractUserVO>) (pager.getResultList()) ;
		setDic( list,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		ListPageVO<ArcLocalContractUserVO> listPage = new ListPageVO<ArcLocalContractUserVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String belongCity = request.getParameter("belongCity");//所在地名称code ARC0025
		String orgCd = request.getParameter("orgCd");//组织架构code
		String orgId = request.getParameter("orgId");//组织架构id
		String userIds = request.getParameter("userIds");//属地合同管理员人员id 以逗号分隔
		ArcLocalContractUserVO entity = new ArcLocalContractUserVO();		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			entity.setBelongCity(belongCity);
			entity.setOrgCode(orgCd);
			if(StringUtils.isNotEmpty(orgId)) {
				entity.setOrgId(Long.parseLong(orgId));
			}
			entity.setUserIds(userIds);
			entity.setIsDel(String.valueOf(ArchiveConstants.IS_DEL));
			entity.setIsValid(String.valueOf(ArchiveConstants.IS_VALID));
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			Long id = this.arcLocalContractUserService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object modify(ArcLocalContractUserVO entity,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			entity.setId(Long.valueOf(id));
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			//TODO ADD PARAM
			boolean success = this.arcLocalContractUserService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 得到一条记录
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			ArcLocalContractUserVO vo = this.arcLocalContractUserService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.GET })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcLocalContractUserService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	/**
	 * 设置数据字典
	 * @param list
	 * @param sysCd
	 * @param orgCd
	 */
	public void setDic(List<ArcLocalContractUserVO> list,String sysCd,String orgCd){
		// 数据字典:权证属地城市配置
		List<KeyValueVO> cityList= this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC_LOCAL_CITY, sysCd, orgCd);
		Map<String, String> contCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, ArchiveConstants.ARC_LOCAL_CONTRACT);
		
		if(list != null && list.size() >0) {
			for (ArcLocalContractUserVO vo : list) {
				//权证属地城市名称
				for (int i = 0; i < cityList.size(); i++) {
					KeyValueVO kv=cityList.get(i);
					if (kv.getKey().equals(vo.getBelongCity())) {
						vo.setBelongCityNm(kv.getValue());
						break;
					}
				}
				//合同管理人员名称
				if (StringUtils.isNotEmpty(vo.getUserIds())) {
					// 合同管理人员名称
					String[] contArray = vo.getUserIds().split(";");
					String userNames = "";
					for (String tcpString : contArray) {
						if (contCdMap.containsKey(tcpString)) {
							userNames += contCdMap.get(tcpString);
							userNames += ";";
						}
					}
					if (StringUtils.isNotEmpty(userNames)) {
						userNames = userNames.substring(0,userNames.length() - 1);
					}
					vo.setUserNames(userNames);
				}
			}
		}
	}
	
	
	
	
}

